package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;
    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO addOrder(OrdersSubmitDTO dto) {
        //校验数据（地址簿是否为空，购物车数据是否为空）
        //购物车数据是否为空
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCartPattern = ShoppingCart.builder()
                .id(currentId)
                .build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryByUserIdAndId(shoppingCartPattern);
        if (Objects.isNull(shoppingCarts) || shoppingCarts.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //地址簿是否为空
        AddressBook address = addressBookMapper.getById(dto.getAddressBookId());
        if (Objects.isNull(address)) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //向订单表添加单条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(address.getPhone());
        orders.setUserId(currentId);
        orders.setConsignee(address.getConsignee());
        orders.setAddress(address.getDetail());
        orderMapper.insert(orders);

        //向订单明细表添加n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertAll(orderDetails);
        //清空购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        shoppingCartMapper.deleteItem(shoppingCart);
        //封装返回数据
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();

        return vo;
    }

    /**
     * 查询历史订单含详细信息
     *
     * @param dto
     * @return Orders+OrderDetails
     */
    @Override
    public PageResult queryHistoryOrders(OrdersPageQueryDTO dto) {
        Long currentId = BaseContext.getCurrentId();
        //分页查询订单
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Orders> list = orderMapper.queryByUserId(currentId);
        Page<Orders> page = (Page<Orders>) list;
        //根据订单查询订单明细，并封装至VO对象
        List<OrderHistoryVO> historyVOList = new ArrayList<>();
        for (Orders orders : page) {
            List<OrderDetail> templist = orderDetailMapper.queryByOrderId(orders.getId());
            OrderHistoryVO historyVO = new OrderHistoryVO();
            historyVO.setOrderDetailList(templist);
            BeanUtils.copyProperties(orders, historyVO);
            historyVOList.add(historyVO);
        }
        //返回VO对象
        return new PageResult(page.getTotal(), historyVOList);
    }

    @Override
    public OrderHistoryVO queryOrderDetailByOrderId(Long id) {
        Orders orders = orderMapper.queryByOrderId(id);
        OrderHistoryVO historyVO = new OrderHistoryVO();
        if (Objects.nonNull(orders)) {
            List<OrderDetail> templist = orderDetailMapper.queryByOrderId(orders.getId());
            historyVO.setOrderDetailList(templist);
            BeanUtils.copyProperties(orders, historyVO);
        }
        return historyVO;
    }

    /**
     * 从订单获取订单快照，将订单数据封装到购物车中并存入当前用户
     *
     * @param orderId
     */
    @Override
    public void repeatOrder(Long orderId) {
        //清空购物车

        //获取订单快照
        List<OrderDetail> originDetails = orderDetailMapper.queryByOrderId(orderId);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        Long currentId = BaseContext.getCurrentId();
        //封装购物车数据
        for (OrderDetail originDetail : originDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(originDetail, shoppingCart);
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertAll(shoppingCartList);
    }

    @Override
    public void cancelOrder(Long orderId) {
        //查询orders对象
        Orders orders = orderMapper.queryByOrderId(orderId);
        //校验orders对象是否存在
        if (Objects.isNull(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //修改orders相关字段
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        //更新orders数据
        orderMapper.updateOrder(orders);
    }

    /**
     * 分页查询，并将菜品数据整理为字符串传回管理端
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult queryHistoryOrdersAndDishes(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //查询订单数据
        List<Orders> ordersList = orderMapper.queryByConditions(dto);
        //根据订单数据查询订单中菜品数据，并封装至OrdersVO对象
        List<OrdersVO> resultList = new ArrayList<>();
        Page<Orders> pages = (Page<Orders>) ordersList;
        for (Orders orders : pages) {
            List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(orders.getId());
            StringBuilder sb = new StringBuilder();
            //获取菜品及菜品口味字符串
            for (OrderDetail orderDetail : orderDetails) {
                sb.append(orderDetail.getName()).append(orderDetail.getDishFlavor()).append(",");
            }
            //封装数据
            OrdersVO ordersVO = new OrdersVO();
            BeanUtils.copyProperties(orders, ordersVO);
            ordersVO.setOrderDishes(sb.toString());
            resultList.add(ordersVO);
        }
        //封装结果并返回
        return new PageResult(pages.getTotal(), resultList);
    }

    @Override
    public OrderStatisticsVO count() {
        return OrderStatisticsVO.builder()
                .toBeConfirmed(orderMapper.count(Orders.TO_BE_CONFIRMED))
                .confirmed(orderMapper.count(Orders.CONFIRMED))
                .deliveryInProgress(orderMapper.count(Orders.DELIVERY_IN_PROGRESS))
                .build();
    }

    @Override
    public void acceptOrder(Long id) {
        //将逻辑放在Mapper中，查询指定行并修改status
        orderMapper.updateStatus(id, Orders.CONFIRMED);
    }

    @Override
    public void rejectOrder(OrdersRejectionDTO dto) {
        //取出订单实例对象
        Orders orders = orderMapper.queryByOrderId(dto.getId());
        //修改数据
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(dto.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        //更新数据库
        orderMapper.updateOrder(orders);
    }

    @Override
    public void cancelOrderByAdmin(OrdersCancelDTO dto) {
        Orders orders = orderMapper.queryByOrderId(dto.getId());

        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(dto.getCancelReason());
        orders.setStatus(Orders.CANCELLED);

        orderMapper.updateOrder(orders);
    }

    @Override
    public void deliverOrder(Long id) {
        orderMapper.updateOrder(Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build());
    }

    @Override
    public void completeOrder(Long id) {
        orderMapper.updateOrder(Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build());
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.updateOrder(orders);

        NotifyVO notifyVO = NotifyVO.builder()
                .type(NotifyVO.New)
                .orderId(ordersDB.getId())
                .content("订单号:" + outTradeNo)
                .build();
        String messageJson = JSON.toJSONString(notifyVO);
        webSocketServer.sendToAllClient(messageJson);
    }

    @Override
    public void reminder(Long orderId) {
        //获取数据库中数据
        Orders orders = orderMapper.queryByOrderId(orderId);
        //校验数据
        if(Objects.isNull(orders) || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        NotifyVO notifyVO = NotifyVO.builder()
                .type(NotifyVO.TO_BE_CONFIRMED)
                .orderId(orderId)
                .content("订单号：" + orders.getNumber())
                .build();
        String notifyString = JSON.toJSONString(notifyVO);
        webSocketServer.sendToAllClient(notifyString);
    }

}









